#include <bits/stdc++.h>
using namespace std;

//核心是反插链表

struct ListNode {
    int val;
    ListNode *next;
    ListNode() : val(0), next(nullptr) {}
    ListNode(int x) : val(x), next(nullptr) {}
    ListNode(int x, ListNode *next) : val(x), next(next) {}
};

class Solution {
public:
    ListNode* reverseKGroup(ListNode* head, int k) {
        ListNode *ans = NULL, *rear = NULL;
        int cnt = 0;
        ListNode *p = head;
        while(p != NULL) {
            ++cnt;
            p = p->next;
        }
        int n = cnt / k;
        p = head;
        // ListNode
        for(int i=0; i<n; ++i){
            ListNode *fragHead = NULL;
            ListNode *fragRear = p;
            for(int j=0; j<k; ++j){ //反插
                ListNode *ap = p->next;
                p->next = fragHead;
                fragHead = p;
                p = ap;
            }
            if(i == 0) {ans = fragHead; rear = fragRear;}
            else {
                rear->next = fragHead;
                rear = fragRear;
            }
        }
        rear->next = p;

        return ans;
    }
};

int main(){

}